package com.wlc.socket.demo01;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author 王立朝 wanglichao@champion-credit.com
 * @description socket 服务端
 * @date 2021-07-15 13:02
 */
public class SocketServer {


    public static void main(String[] args) {
        method01();
    }

    /**
     * 服务端接收客户端发送的信息
     */
    private static void method01() {
        // 服务端打开端口

        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            // 服务端时刻监听着是否有客户端连接进来
            Socket accept = serverSocket.accept();
            System.out.println("有连接进来 " + accept);

            // 获取输入流，获取客户端发送的信息
            InputStream inputStream = accept.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);

            // 服务端输出
            OutputStream outputStream = accept.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            while (true) {
                Scanner sc = new Scanner(System.in);
                System.out.println("服务端接收到的信息为：" + dataInputStream.readUTF());
                String line = sc.next();
                dataOutputStream.writeUTF(line);
                System.out.println("服务端发送完毕");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
